import logging
import json
from typing import Dict, Any

# 配置日志
logger = logging.getLogger(__name__)
logger.setLevel(logging.INFO)

# 尝试导入所需模块
try:
    from fastapi import APIRouter, Request, HTTPException
    from fastapi.responses import JSONResponse
    from app.services.shopify_translate_service import shopify_translate_service
except ImportError as e:
    logger.error(f"导入模块失败: {str(e)}")
    # 提供备用实现
    class MockRouter:
        def post(self, path: str, **kwargs):
            def decorator(func):
                self.endpoint = func
                return func
            return decorator
    
    class MockRequest:
        def __init__(self, headers=None, body=None):
            self.headers = headers or {}
            self.body = body
    
    APIRouter = MockRouter
    Request = MockRequest
    JSONResponse = lambda content: content

# 创建路由实例
router = APIRouter(prefix="/api/v1", tags=["shopify_batch_translate"])

@router.post("/batch-translate-all-products", response_model=Dict[str, Any])
async def batch_translate_all_products(request: Request):
    """
    批量翻译店铺所有产品并写入metafields
    
    请求体参数:
    - shopify_domain: str - Shopify店铺域名
    - namespace: str (可选) - Metafield命名空间，默认为'translate_namespace'
    - key: str - Metafield键名
    - ori_text: str - 需要翻译的原始文本
    - target_language: str - 目标语言代码
    - type: str (可选) - Metafield类型，默认为'single_line_text_field'
    """
    try:
        # 检查请求内容类型
        content_type = request.headers.get('Content-Type', '')
        if not content_type.startswith('application/json'):
            logger.warning(f"不支持的内容类型: {content_type}")
            return JSONResponse(
                status_code=400,
                content={
                    "is_success": 0,
                    "error": "Invalid content type, application/json required"
                }
            )
        
        # 解析请求体
        try:
            body = await request.body()
            data = json.loads(body)
            logger.info(f"接收批量翻译请求，店铺: {data.get('shopify_domain')}")
        except json.JSONDecodeError:
            logger.error("请求体JSON格式错误")
            return JSONResponse(
                status_code=400,
                content={
                    "is_success": 0,
                    "error": "Invalid JSON format"
                }
            )
        except Exception as e:
            logger.error(f"解析请求体失败: {str(e)}")
            return JSONResponse(
                status_code=400,
                content={
                    "is_success": 0,
                    "error": "Failed to parse request body"
                }
            )
        
        # 提取参数
        shopify_domain = data.get('shopify_domain')
        namespace = data.get('namespace')
        key = data.get('key')
        ori_text = data.get('ori_text')
        target_language = data.get('target_language')
        type = data.get('type')
        
        # 调用服务层执行批量翻译
        result = shopify_translate_service.batch_translate_all_products(
            shopify_domain=shopify_domain,
            namespace=namespace,
            key=key,
            ori_text=ori_text,
            target_language=target_language,
            type=type
        )
        
        # 返回结果
        if result.get('is_success') == 1:
            return JSONResponse(
                status_code=200,
                content=result
            )
        else:
            return JSONResponse(
                status_code=400 if 'Missing required parameters' in result.get('error', '') else 500,
                content=result
            )
            
    except Exception as e:
        logger.error(f"批量翻译请求处理失败: {str(e)}", exc_info=True)
        return JSONResponse(
            status_code=500,
            content={
                "is_success": 0,
                "error": "Internal server error",
                "details": str(e)
            }
        )

# 导出路由供主应用使用
__all__ = ['router']